﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Luna;

namespace TextDataExtractor.DEML {

	public class DemlRegistry {
		private IList<AbstractPattern> patterns;


		public event EventHandler<DemlEventArg> Event;

		public DemlRegistry() {
			patterns = new List<AbstractPattern>();
		}

		public IList<AbstractPattern> Patterns {
			get {
				return patterns;
			}
		}

		public T fireEvent<T>(DemlEventArg arg, T defReturn = default(T)) {
			T result = defReturn;
			if (Event != null) {
				Event(this, arg);
				if (arg.Feedback is T)
					result = (T)arg.Feedback;
			}
			return result;
		}

		public AbstractPattern findPattern(string name) {
			if (name.isNotNullAndEmpty())
				return patterns.FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
			return null;
		}

		public void loadPatterns(XmlDocument doc) {
			XmlNode root = doc.SelectSingleNode("/deml/patterns");
			if (root != null)
				foreach (XmlNode child in root) {
					AbstractPattern pattern =  (AbstractPattern) DemlFactory.Instance.createElement(ElementType.Pattern, child.Name);
					if (pattern != null) 
						pattern.loadFromXml(child, this);
					Patterns.Add(pattern);
				}
		}

		public void loadPatterns(string demlFilename) {
			XmlDocument doc = new XmlDocument();
			doc.Load(demlFilename);
			loadPatterns(doc);
		}
	}

	public enum DemlEvent { Unknown, BeginMatch }

	public class DemlEventArg : EventArgs {
		public DemlEvent Event { get; private set; }
		public DemlElement Element { get; private set; }
		public object Context { get; private set; }
		public object Feedback { get; set; }

		public DemlEventArg(DemlEvent @event, DemlElement element, object context) {
			this.Event = @event;
			this.Context = context;
			this.Element = element;
		}
	}
}
